const express = require('express')
const router = express.Router()
const service = require("../service/user");

// 登录接口
router.post('/login', async (req, res) => {
  console.log("req.body: ",req.body);
  const {ref,address} = req.body;

  const user=await service.getByAddress(address);
  console.log("user: ",user);
  if(user){
    res.json({ code: 0, message: '登录成功',data:user })
    return;
  }

  const refUser=await service.getByAddress(ref);
  console.log("refUser: ",refUser);
  if(!refUser){
    res.json({ code: 600, message: '请使用邀请链接访问'})
    return;
  }

  req.body.pid=refUser.id;
  await service.save(req.body);

  const user_new=await service.getByAddress(address);
  res.json({ code: 0, message: '登录成功',data:user_new })
})

// 绑定接口
router.post('/active', async (req, res) => {
  console.log("req.body: ",req.body);
  const {address} = req.body;
  await service.active(address);
  res.json({ code: 0, message: '激活成功' })
})

// 绑定接口
router.post('/bind', async (req, res) => {
  console.log("req.body: ",req.body);
  service.update(req.body);
  res.json({ code: 0, message: '绑定成功' })
})


// 绑定接口
router.get('/endTime', async (req, res) => {
  const curDate = new Date();
  const endDate = new Date("2025-03-31T20:00:00+08:00");
  console.log("curDate:",curDate+" endDate:",endDate);
  var diff = Math.abs(endDate.getTime() - curDate.getTime());
  var diffInSeconds = Math.floor(diff / 1000);
  if(diffInSeconds<0){
    diffInSeconds=0;
  }
  res.json({ code: 0, message: '绑定成功',data:{end_datetime:endDate,end_seconds:diffInSeconds} })
})


module.exports = router